package com.ccdc.cbpc.bigdata.open.common.vo;

import com.ccdc.cbpc.bigdata.open.common.enums.RespCodeEnum;
import com.ccdc.cbpc.bigdata.open.common.exception.BusinessException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageSerializable;
import lombok.Data;
import java.io.Serializable;
import java.util.Collection;

/**
 * 统一响应处理
 * @author  dong.zhang8
 * @date 2021-07-15
 * @param <T>
 */
@Data
public class BaseRepVO<T> extends BaseVO implements Serializable {
    /**异常码*/
    private Integer code;
    /**异常信息*/
    private String msg;
    /**响应信息*/
    private T data;
    /**总记录数*/
    private Integer count;

    public BaseRepVO(){
        this(RespCodeEnum.SUCCESS);
    }
    public BaseRepVO(T data){
        this(data,null);
        if (data != null) {
            // 检查pageHelper
           if(data instanceof Page){
                Page data1 = (Page) data;
                this.data = (T) data1.getResult();
                try {
                    this.count = Long.valueOf(data1.getTotal()).intValue();
                }catch (Exception e){
                    throw new BusinessException("数据超过Integer最大值！");
                }
            }else if(data instanceof PageSerializable){
                PageSerializable data1 = (PageSerializable) data;
                this.data = (T) data1.getList();
                try {
                    this.count = Long.valueOf(data1.getTotal()).intValue();
                }catch (Exception e){
                    throw new BusinessException("数据超过Integer最大值！");
                }
            }else if(data instanceof Collection){
               // 检查pageHelper须在集合接口之前
                Collection data1 = (Collection) data;
                this.count = data1.size();
            }
        }
    }
    public BaseRepVO(T data,Integer count){
        this(RespCodeEnum.SUCCESS);
        this.data = data;
        this.count = count;
    }
    public BaseRepVO(String msg){
        this(RespCodeEnum.SERVER_ERROR, msg);
    }
    public BaseRepVO(RespCodeEnum respCodeEnum) {
        this(respCodeEnum.getCode(),respCodeEnum.getDesc());
    }
    public BaseRepVO(BusinessException e){
        this(e.getErrorCode(),e.getMessage());
    }
    public BaseRepVO(RespCodeEnum respCodeEnum,String msg) {
        this.code = respCodeEnum.getCode();
        this.msg = msg;
    }

    public BaseRepVO(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    public static BaseRepVO SUCCESS = new BaseRepVO();
}
